<script lang="ts" setup>
import { message } from 'ant-design-vue';
import type { PropType } from 'vue';
import { watch } from 'vue';
import { useExamListStore } from '@/store/modules/dcp/enginee_certification/examList';

const props = defineProps({
  visible: {
    type: Boolean as PropType<boolean>,
  },
  getVisible: {
    type: Function as PropType<() => void>,
    required: true,
  },
});
const examListStore = useExamListStore();
const examList = ref<any[]>([]);
const exam = ref<any[]>([]);
const selectedExamName = ref<string>('');
const examDates = ref<string[]>([]);
const examEvent = ref<string[]>([]);
onMounted(async () => {
  await examListStore.getExamList();
  examList.value = examListStore.examList;
  exam.value = examListStore.getExam();
  updateExamDates(selectedExamName.value); // 初始化examDates
  // updateExamEvent(selectedExamName.value)
});

const formRef = ref();
const form = ref({
  examName: '',
  name: '',
  phone: '',
  examDate: '',
  personCode: '',
  examEvent: '',
});

const rules: any = {
  name: [{ required: true, message: '请输入报考人姓名！' }],
  examName: [{ required: true, message: '请选择考试！' }],
  phone: [{ required: true, message: '请输入报考人电话！' }],
  examDate: [{ required: true, message: '请选择考试日期！' }],
  personCode: [{ required: true, message: '请输入人员编号！' }],
  examEvent: [{ required: true, message: '请选择考试场次！' }],
};

interface ExamRegistration {
  examName: string
  name: string
  phone: string
  examDate: string
  personCode: string
  examEvent: string
}

function resetForm() {
  formRef.value.resetFields();
  examDates.value = [];
  selectedExamName.value = '';
}

function onClose() {
  props.getVisible();
}

function convertDateToYYYYMMDD(dateStr: string): string {
  const regex = /^(\d{1,2})月(\d{1,2})日$/;
  const matches = dateStr.match(regex);
  if (!matches) {
    return '';
  }
  const month = Number.parseInt(matches[1], 10);
  const day = Number.parseInt(matches[2], 10);
  const now = new Date();
  const year = now.getFullYear(); // 默认当前年份

  return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
}

async function onSubmit() {
  try {
    await formRef.value.validate();
    const formattedExamDate = convertDateToYYYYMMDD(form.value.examDate);
    if (!formattedExamDate) {
      message.error('无效的考试日期格式');
      return;
    }
    const registrationData: ExamRegistration = {
      examName: form.value.examName,
      name: form.value.name,
      phone: form.value.phone,
      examDate: formattedExamDate,
      personCode: form.value.personCode,
      examEvent: form.value.examEvent,
    };
    await examUseradd(registrationData);
    message.success('提交成功');
    props.getVisible();
  }
  catch (error) {
    message.error('表单验证失败或提交失败');
  }
}

function updateExamDates(level: any) {
  examDates.value = [];
  const examInfo = examList.value.find(item => item.examName === level);
  if (examInfo) {
    for (let i = 0; i < examInfo.examDates.length; i++) {
      examDates.value.push(examInfo.examDates[i].date);
    }
  }
  else {
    examDates.value = [];
  }
}
const newLevel = ref<string>('');
function updateExamEvent(date: any) {
  examEvent.value = [];
  // 根据日期再匹配场次
  const examInfo = examList.value.find(item => item.examName === newLevel.value);
  let count = 0;
  if (examInfo) {
    for (let i = 0; i < examInfo.examDates.length; i++) {
      if (examInfo.examDates[i].date === date) {
        examEvent.value.push(examInfo.examDates[i].event);
        count++;
      }
    }
  }
  else {
    examEvent.value = [];
  }
  if (count === 0) {
    examEvent.value = [];
  }
}

watch(() => form.value.examName, (newVal) => {
  updateExamDates(newVal);
  newLevel.value = newVal;
});
watch(() => form.value.examDate, (newVal) => {
  form.value.examEvent = '';
  updateExamEvent(newVal);
});
</script>

<template>
  <div>
    <a-drawer
      title="考试报名" :width="720" :visible="props.visible" :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <a-form ref="formRef" :model="form" layout="vertical" :rules="rules">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="考试名称" name="examName">
              <a-select v-model:value="form.examName" placeholder="请选择考试">
                <a-select-option v-for="item in examList" :key="item.examName" :value="item.examName">
                  {{ item.examName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="报考人编号" name="personCode" prop="personCode">
              <a-input v-model:value="form.personCode" placeholder="请输入报考人编号" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="报考人姓名" name="name">
              <a-input v-model:value="form.name" placeholder="请输入报考人姓名" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="报考人手机号" name="phone">
              <a-input v-model:value="form.phone" placeholder="请输入报考人手机号" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="考试日期" name="examDate">
              <a-select v-model:value="form.examDate" placeholder="请选择考试日期">
                <a-select-option v-for="date in examDates" :key="date" :value="date">
                  {{ date }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="考试场次" name="examEvent">
              <a-select v-model:value="form.examEvent" placeholder="请选择考试场次(先选择考试日期)">
                <a-select-option v-for="event in examEvent" :key="event" :value="event">
                  {{ event }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button style="margin-right: 8px;" @click="onClose">
          取消
        </a-button>
        <a-button style="margin-right: 8px;" @click="resetForm">
          重置
        </a-button>
        <a-button type="primary" @click="onSubmit">
          提交
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>
